/* 
 * @name administration.js
 * @author : Amissah Gideon<kuulmek@yahoo.com>
 */
var Items = {
    /* Server script url   */
    ssUrl:'Items/add',
    selected_row_id:null,

    /* dataTable Object */
    objGrid:null,

    /* Function init
     * @param void
     * @return void
     * @access public
     * */
    init:function () {
        var self = this;
        /*Sortable Table */
        var oTable = null;
        var dataUrl = $('#table-url').val();

        self.objGrid = $('#flex').flexigrid({
            url:dataUrl,
            dataType:'json',
            colModel:[
                {display:'ID', name:'id', width:20, sortable:false, align:'left', hide:true},
                {display:'Name', name:'name', width:240, sortable:true, align:'center', hide:false},
                {display:'Specs', name:'specs', width:100, sortable:true, align:'center', hide:false},
                {display:'Currency', name:'currency', width:60, sortable:true, align:'center', hide:false},
                {display:'Amount', name:'amount', width:140, sortable:true, align:'center', hide:false},
                {display:'USD Rate', name:'usd_rate', width:80, sortable:true, align:'center', hide:false},
                {display:'Cedi Equivalent (GHS)', name:'cedi_amount', width:140, sortable:true, align:'center', hide:false},
                {display:'Comments', name:'comments', width:140, sortable:true, align:'center', hide:false}
            ],
            formFields:[
                {type:'buttom', name:'Add', bclass:'add', onpress:self.handleGridEvent},
                {separator:true},
                {type:'buttom', name:'Edit / View', bclass:'edit', onpress:self.handleGridEvent},
                {separator:true},
                {type:'buttom', name:'Delete', bclass:'delete', onpress:self.handleGridEvent}
            ],
            searchitems:[
                {display:'Name', name:'name', isdefault:true}
            ],
            checkboxSelection:true,
            columnControl:true,
            sortname:"id",
            sortorder:"desc",
            usepager:true,
            useRp:true,
            rp:15,
            showTableToggleBtn:false,
            height:300
        });

        var editorTextarea = $('#specs'),
        editorWrapper = editorTextarea.parent(),
        editor = editorTextarea.cleditor({
            width:	'400px',
            height:	250,
            controls:"bold italic underline | bullets numbering | outdent indent | alignleft center alignright justify | undo redo"
        })[0];
        // Update size when resizing
        editorWrapper.sizechange(function(){
            editor.refresh();
        });

        $('#save-btn').click(function () {
            self.save();
        });

        $('#cancel-btn').click(function () {
            document.getElementById('form').reset();
            $.validationEngine.closePrompt('.formError', true);
            $.colorbox.close();
            self.selected_row_id = null;
        });

        jLib.afterClosePopUpForm('form', function () {
            self.selected_row_id = null;
            document.getElementById('form').reset();
        });

        $("#form").validationEngine();
    },

    handleGridEvent:function (com, grid) {
        if (com == 'Add') {
            $.colorbox({
                inline:true,
                scrolling:false,
                overlayClose:false,
                escKey:false,
                title:'Items Information',
                href:"#form-window"
            });
        }
        else if (com == 'Edit / View') {
            if (jLib.rowSelectedCheck(grid, 1)) {
                Items.edit(jLib.getSelectedRowIds(grid));
            }
        }
        else if (com == 'Delete') {
            if (jLib.rowSelectedCheck(grid)) {
                Items.delete_(grid);
            }
        }
    },

    edit:function (row_ids) {

        var self = this;
        var dataID = row_ids[0];
        var url = $('#load-user-url').val();
        var query = 'type=load&data-id=' + dataID;

        $.ajax({
            url:url,
            data:query,
            dataType:'json',
            type:'POST',
            success:function (response) {
                var txt = '';
                if (typeof response.mesg == 'object') {
                    for (megTxt in response.mesg) {
                        txt += response.mesg[megTxt] + '<br />';
                    }
                }
                else {
                    txt = response.mesg
                }
                //* When everything went on smoothly on the server redirect the user to the appropriate page.*//*
                if (response.code === 0) {
                    var data = response.data.Item;

                    $('#form-window #form #name').val(data.name);
                    //$('#form-window #form #name').change();
                    $('#form-window #form #specs').val(data.specs);
                    $('#form-window #form #currency').val(data.currency);
                    $('#form-window #form #currency').change();
                    $('#form-window #form #amount').val(data.amount);
                    $('#form-window #form #usd_rate').val(data.usd_rate);
                    $('#form-window #form #insurance_currency').val(data.insurance_currency);
                    $('#form-window #form #insurance_currency').change();
                    $('#form-window #form #insurance_amt').val(data.insurance_amt);
                    $('#form-window #form #comments').val(data.comments);

                    self.selected_row_id = dataID;

                    $.colorbox({
                        inline:true,
                        scrolling:false,
                        overlayClose:false,
                        escKey:false,
                        title:'Item Information',
                        href:"#form-window"
                    });
                }
                //* When there are Errors *//*
                else if (response.code === 1) {
                    jLib.serverError(txt);
                }
            },
            error:function (xhr) {
                console.log(xhr.responseText);
                jLib.serverError();
            }
        });
    },

    save:function () {
        var self = this;
        /* Validate the form*/
        var validationStatus = $('#form').validationEngine({returnIsValid:true});
        /* When the Validation Status is true meaning that the data input are correct then the data can be processed. */
        if (validationStatus) {

            jLib.showFormLoading();

            var query = 'model=Item&row_id=' + self.selected_row_id + '&' + $('#form').serialize();
            var url = $("#add-edit-url").val();
            /* Send the data to the server and handle the server response */

            $.ajax({
                url:url,
                data:query,
                dataType:'json',
                type:'POST',
                success:function (response) {
                    var txt = '';
                    if (typeof response.mesg == 'object') {
                        for (megTxt in response.mesg) {
                            txt += response.mesg[megTxt] + '<br />';
                        }
                    }
                    else {
                        txt = response.mesg
                    }
                    //* When everything went on smoothly on the server redirect the user to the appropriate page.*//*
                    if (response.code === 0) {

                        jLib.message(txt, 'success');

                        if(self.selected_row_id){

                            var cedi_amount = 0.00;
                            if ($('#form-window #form #currency').val() == '$') {
                                cedi_amount = parseFloat($('#form-window #form #amount').val()) * parseFloat($('#form-window #form #usd_rate').val());
                            }
                            else {
                                cedi_amount = $('#form-window #form #amount').val();
                            }
                            // Chnge the cell data
                            var update_data = {
                                'name':$('#form-window #form #name').val(),
                                'specs':$('#form-window #form #specs').val(),
                                'currency':$('#form-window #form #currency').val(),
                                'amount':$('#form-window #form #amount').val(),
                                'usd_rate':$('#form-window #form #usd_rate').val(),
                                'cedi_amount':cedi_amount,
                                'comments':$('#form-window #form #comments').val()
                                //'status': $('#form-window #form #routine_status option:selected').text(),
                            };

                            jLib.updateGridData(self.objGrid, update_data);
                            //
                            jLib.highlightRow(self.objGrid);
                        }
                        else{
                            $(self.objGrid).flexReload();
                        }
                        document.getElementById('form').reset();
                        $.validationEngine.closePrompt('.formError',true);
                        $.colorbox.close();
                        self.selected_row_id = null;
                    }
                    //* When there are Errors *//*
                    else if (response.code === 1) {
                        jLib.serverError(txt);
                    }

                    jLib.hideFormLoading();
                },
                error:function (xhr) {
                    console.log(xhr.responseText);
                    jLib.serverError();
                }
            });
        }
    },


    delete_:function (grid) {
        var self = this;
        var url = $('#delete-url').val();
        jLib.do_delete(url, grid);
    }

};

/* when the page is loaded */
$(document).ready(function () {
    Items.init();
});